import json
import xmltodict
from django.http.request import HttpRequest
from django.http.response import JsonResponse
import jenkins
from django.views import View

jenkinsUrl = "http://127.0.0.1:8090"
jenkinsUser = "admin"
jeninsPass = "admin"

jenkinsConn = jenkins.Jenkins(jenkinsUrl,jenkinsUser,jeninsPass)

jobxml = """<?xml version='1.1' encoding='UTF-8'?>
<flow-definition plugin="workflow-job@2.40"> 
    <actions>   
        <org.jenkinsci.plugins.pipeline.modeldefinition.actions.DeclarativeJobAction plugin="pipeline-model-definition@1.8.4"/>
        <org.jenkinsci.plugins.pipeline.modeldefinition.actions.DeclarativeJobPropertyTrackerAction plugin="pipeline-model-definition@1.8.4\">     
            <jobProperties/>
            <triggers/>
            <parameters/>
            <options/>
        </org.jenkinsci.plugins.pipeline.modeldefinition.actions.DeclarativeJobPropertyTrackerAction>
    </actions>
    <description></description>
    <keepDependencies>false</keepDependencies>
    <definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps@2.90">   
        <script>pipeline {\n    agent any\n\n    stages {\n        stage(&apos;Hello&apos;) {\n            steps {\n                echo &apos;Hello World&apos;\n            }\n        }\n    }\n}\n</script>\n
        <sandbox>true</sandbox>\n
        <sandbox>true</sandbox>
    </definition>
    <triggers/>
    <disabled>false</disabled>
</flow-definition>"""

class jenkinsPlug(View):
    @staticmethod
    def post(request):
        
        plugins = jenkinsConn.get_plugins_info()
        print(plugins)

        return JsonResponse(plugins,safe=False)


class jenkinsCreateJob(View):
    @staticmethod

    def post(request):
        newJob = jenkinsConn.create_job('empty11',jobxml)


        return JsonResponse(newJob,safe=False)

class jenkinsGetJobConfig(View):
    @staticmethod
    def post(request):
        getJobConfig = jenkinsConn.get_job_config("empty1")

        print(json.dumps(xmltodict.parse(getJobConfig)))

        return JsonResponse(getJobConfig,safe=False)    
